<?php
class CategoryController extends Epic_Controller_Action 
{	
	/**
	 * Authentication
	 * 
	 * @see Epic_Controller_Action::init()
	 * @return void;
	 */
	public function init() 
	{
		if (!Epic::getSession()->get('role')) {
			$this->_redirect(Epic::getUrl());
		}
	}
	
	public function indexAction() { }
	
	public function newAction() {}
	
	public function editAction()
	{
		$id = $this->getRequest()->getParam('id');
		$model  = Epic::getModel('blog/category')->load($id);
		if ($model) {
			Epic::setFormData($model);
		}  else {
			Epic::setError('Category does not exist');
			$this->_redirect(Epic::getUrl('blog/category/index'));
		}
	}
	
	public function saveAction() 
  	{  	
  		if ($this->getRequest()->getPost()) {
			try {
				// validate
				$name = $this->getRequest()->getPost('name');
				if (empty($name)) {
					Epic::setFormData($this->getRequest()->getPost());
					Epic::setError('Name is not empty');
					
					if ($this->getRequest()->getPost('category_id'))
						$this->_redirect(Epic::getUrl('blog/category/edit', array('id' => $this->getRequest()->getPost('category_id'))));
					else
						$this->_redirect(Epic::getUrl('blog/category/new'));
				}
				
				// save data
				Epic::getModel('blog/category')->save($this->getRequest()->getPost());
				
				Epic::setFormData(false); // reset form data
				Epic::setSuccess('The category has been saved.');
			} catch (Exception $e) {
				Epic::setError($e->getMessage());
			}
  		} else {
  			Epic::setError('Unable to find category to save');
  		}
  		$this->_redirect(Epic::getUrl('blog/category/index'));
	}
	
	/**
	 * Delete category by Id
	 */
	public function deleteAction() {
		if( $this->getRequest()->getParam('id') > 0 ) {
			try {
				Epic::getModel('blog/category')->delete($this->getRequest()->getParam('id'));
				Epic::setSuccess('The category #' . $this->getRequest()->getParam('id') . ' has been deleted.');
			} catch (Exception $e) {
				Epic::setError($e->getMessage());
			}
		}
		$this->_redirect(Epic::getUrl('blog/category/index'));
	}
}